package com.zyguo.sdk.http;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.concurrent.Callable;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.apache.log4j.Logger;

import com.zyguo.sdk.common.AbstractTask;

public class HttpThreadPool extends AbstractTask<HttpResponse> implements IHttp {
	private static Logger log = Logger.getLogger( HttpThreadPool.class );

	@Override
	public boolean postByAsyn(final String url, final List<NameValuePair> params) {
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				post(url, params);
			}
		};
		return asynDoTask( runnable );
	}
	
	public static HttpResponse post(String url, List<NameValuePair> params ) {
		long begin = System.currentTimeMillis();
		HttpResponse response = null;
		try {
			DefaultHttpClient client = new DefaultHttpClient();
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
			HttpPost postMethod = new HttpPost(url);
			postMethod.setEntity(entity);// 设置请求实体，例如表单数据
			response = client.execute(postMethod);
			return response;
		} catch (Exception e) {
			log.error("post 异常, url=" + url + ",params=" + params, e);
		} finally {
			long end = System.currentTimeMillis();
			log.debug("post 耗时=" + (end - begin) + "毫秒" + ",url=" + url + ",params=" + params + ",response" + response );  
		}
		return null;
	}
	
	@Override
	public HttpResponse postBySync(String url, List<NameValuePair> params) {
		return this.postBySync(url, params, DEFAULT_MAX_WAIT_SEC);
	}

	@Override
	public HttpResponse postBySync(final String url, final List<NameValuePair> params, int maxWaitSec) {
		Callable<HttpResponse> callable = new Callable<HttpResponse>() {
			@Override
			public HttpResponse call() throws Exception {
				return post(url, params);
			}
		};
		
		try {
			return syncDoTask( callable, maxWaitSec );
		} catch (Exception e) {
			log.error("postBySync future.get 异常, url=" + url + ",params=" + params, e);
		}
		return null;
	}

	@Override
	public boolean httpsByAsyn(final String url, final List<NameValuePair> params) {
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				https(url, params);
			}
		};
		return asynDoTask( runnable );
	}

	private HttpResponse https(String url, List<NameValuePair> params) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		X509TrustManager tm = new X509TrustManager() {
			public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {

			}

			public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
			}

			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};
		
		try {
			SSLContext ctx = SSLContext.getInstance("SSL");
			ctx.init(null, new TrustManager[] { tm }, null);
			SSLSocketFactory ssf = new SSLSocketFactory(ctx);

			ClientConnectionManager ccm = httpclient.getConnectionManager();
			// register https protocol in httpclient's scheme registry
			SchemeRegistry sr = ccm.getSchemeRegistry();
			sr.register(new Scheme("https", 443, ssf));

			HttpGet httpget = new HttpGet( url );
			HttpParams params2 = httpclient.getParams();

			params2.setParameter("param1", "paramValue1");

			httpget.setParams(params2);
			System.out.println("REQUEST:" + httpget.getURI());
			ResponseHandler responseHandler = new BasicResponseHandler();
			String responseBody = null;
			System.out.println(responseBody);	
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return null;

		
	}

	@Override
	public HttpResponse httpsBySync(String url, List<NameValuePair> params) {
		return this.httpsBySync(url, params, DEFAULT_MAX_WAIT_SEC);
	}

	@Override
	public HttpResponse httpsBySync(final String url, final List<NameValuePair> params, int maxWaitSec) {
		Callable<HttpResponse> callable = new Callable<HttpResponse>() {
			@Override
			public HttpResponse call() throws Exception {
				return https(url, params);
			}
		};
		
		try {
			return syncDoTask(callable, maxWaitSec);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
